package edu.cmu.ece.ds.droidchat;

import edu.cmu.ece.ds.droidchat.NetworkService.LocalBinder;
import edu.cmu.ece.ds.droidchat.message.ClientRegisterResponseMessage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity {
    
	public static final String TAG = "Register"; // Debugging TAG
	// Layout Views
	private Button mRegisterButton;
	private TextView mUsername;
	private TextView mPassword;
	
	private NetworkService mService; // the Service component
	private boolean mBound = false;
	
	private Dialog register_dialog = null ;
	private ServerMessageReceiver mReceiver; // the BroadcastReceiver component
	
	private boolean isRegistering = false; 
	
	// The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
            	Log.i(TAG, "Enter Key is pressed"); // info
            }
            return true;
        }
    };
	
    public class ServerMessageReceiver extends BroadcastReceiver {
    	public static final String TAG = "ServerMessageReceiver";
    	public void onReceive(Context context, Intent intent) {
    		Log.d(TAG, "onReceive: " + intent);
    		String username = intent.getStringExtra("username");
    		int response = intent.getIntExtra("response", 0);
    		Log.d(TAG, "username: " + username);
    		Log.d(TAG, "response: " + response);
    		
    		if (isRegistering) {
    			register_dialog.dismiss();
    			if (response==ClientRegisterResponseMessage.REGISTER_SUCCESSFUL) {
    				Toast.makeText( getApplicationContext(), "Registration request with username='" 
    						+ username + "' was successful!", Toast.LENGTH_LONG).show();
    			} else {
    				Toast.makeText( getApplicationContext(), "Registration request with username='" 
    						+ username + "' was NOT successful because it has already been registered!", Toast.LENGTH_LONG).show();
    			}
    		}// else i really don't care
    	}
    }
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);
		Log.d(TAG, "---onCreate---"); 
		
		mRegisterButton = (Button)findViewById(R.id.register);
        mUsername = (EditText) findViewById(R.id.username);
        mPassword = (EditText) findViewById(R.id.password);
        
        // Initialize the username and password field with a listener for the "return key"
        mUsername.setOnEditorActionListener(mWriteListener);
        mPassword.setOnEditorActionListener(mWriteListener);
        
        mReceiver = new ServerMessageReceiver();
        IntentFilter filter = new IntentFilter();
		filter.addAction("edu.cmu.ece.ds.droidchat.message.ClientRegisterResponse");
		Log.d(TAG, "ServerMessageReceiver registered! ");
		this.registerReceiver(mReceiver, filter);
    }
    
    @Override
    public void onStart() {
        super.onStart();
		Log.d(TAG, "---onStart---");
       
        Intent intent = new Intent(this, NetworkService.class);
        Log.d(TAG, "calling bindService()");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        
        // Initialize the Register button with a listener that for click events
        mRegisterButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Opens Socket to contact the servers
            	Log.d(TAG, "Register Button is pressed");
            	
				if(mUsername.getText().toString().equals("")){
            		Log.d(TAG, "username is not entered");
            		Toast.makeText( getApplicationContext(), "You must enter your username and your password to Register", Toast.LENGTH_SHORT).show();
            	}else if(mPassword.getText().toString().equals("")){
            		Log.d(TAG, "password is not entered");
            		Toast.makeText( getApplicationContext(), "You must enter your username and your password to Register", Toast.LENGTH_SHORT).show();
            	}else{
            		Log.d(TAG, mUsername.getText().toString());
                	Log.d(TAG, mPassword.getText().toString());
                	
                	if(mService.isConnectedToServer()){
                		Log.d(TAG, "TCPService has a connection with server");
                	}else{
                		Log.d(TAG, "TCPService does NOT have a connection with server");
                	}
                	
                	if (mBound==true) {
                		if (mService.isConnectedToServer()) {
	                		Log.d(TAG, "mBound is true");
	                		// asks the service to send ClientRegisterMessage to the DroidChat server
	                		mService.register(mUsername.getText().toString(), mPassword.getText().toString());
	                		isRegistering = true;
	                		showDialog(REGISTERING_ID);
                		} else {
                			Toast.makeText( getApplicationContext(), "DroidChat server seems to be down... Please try again later", Toast.LENGTH_SHORT).show();
                		}
                	}
            	}
            }
        });
    }
    
    // most likely the user pressed back to go back to the LogInActivity
	public void onStop() {
    	super.onStop();
    	Log.d(TAG, "---onStop---");
    	Log.d(TAG, "---calling unbindService---");
    	unbindService(mConnection);
    	/*Log.d(TAG, "---finishing RegisterActivity---");
    	finish();*/
    }
	
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "---onDestroy---");
		unregisterReceiver(mReceiver);
	}
	
	/** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to TCPService, cast the IBinder and get TCPService instance
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
			Log.d(TAG, "We've bound to TCPService");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}
    };
    
    static final int REGISTERING_ID = 0;
    
    protected Dialog onCreateDialog(int id){
		Dialog dialog;
		switch(id){
			case REGISTERING_ID:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Registering... Please Wait")
					   .setCancelable(false) // cannot be cancelled by the BACK key, use 'ABORT'
					   .setNegativeButton("Abort", new
							   DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									dialog.cancel();
								}
							});
				dialog = builder.create();
				break;
			default:
				dialog = null;
		}
		register_dialog = dialog;
    	return dialog;
    }
}